import {useSyncExternalStore} from "react";
import {Client} from "@stomp/stompjs";
import StompClientManager from "@/services/stomp/stomp-client";
import {useChatMessageActions} from "@/hooks/chat/chat-message";
import {useChatSessionActions} from "@/hooks/chat/chat-session";
import StompSubscriptionManager from "@/services/stomp/stomp-subscription";

type StompServiceReturnProps = {
  client: Client | null;
  connected: boolean;
  connect: () => void;
  disconnect: () => void;
};

const subscribeManager = new StompSubscriptionManager();

export function useStompClient(): StompServiceReturnProps {
  const connected = useSyncExternalStore(
    (cb) => {
      const interval = setInterval(() => {
        cb();
      }, 100);
      return () => clearInterval(interval);
    },
    () => {
      return StompClientManager.isConnected();
    }
  );

  return {
    client: StompClientManager.getClient(),
    connected,
    connect: () => {
      console.log("🔌 正在连接STOMP服务器...");
      StompClientManager.connect();
    },
    disconnect: () => {
      console.log("🔌 正在断开STOMP连接...");
      StompClientManager.disconnect();
    },
  };
}
